package Server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class Server extends Thread {
	private ServerSocket ss;
	private MailBox mail;
	private ReadMailBoxThread read;
	private ArrayList<ConnectedClient> clients;
	public Game game;

	public Server() {
		clients = new ArrayList<>();
		try {
			ss = new ServerSocket(50000);
			mail = new MailBox();
			read = new ReadMailBoxThread(this, mail);
			read.start();
			System.out.println("Server running...");

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public void run() {
		while (true) {
			try {
				Socket socket = ss.accept();
				if (socket != null) {
					System.out.println(socket.getInetAddress().toString()
							+ " connected");
					ConnectedClient client = new ConnectedClient(socket, mail);
					clients.add(client);

					if (clients.size() == 1) {
						game = new Game(this, clients);
					}
					
					client.setGame(game);

					game.updateClientList();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void sendToAll(String mess, byte packageType) {
		ArrayList<ConnectedClient> clientsToRemove = new ArrayList<>();
		for (ConnectedClient c : clients) {
			if (c.isConnected()) {
				c.send(mess, packageType);
			} else {
				clientsToRemove.add(c);
			}
		}
		
		for(ConnectedClient c:clientsToRemove){
			clients.remove(c);
		}
	}

}
